﻿using System.Linq;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace SmartCity.Shared
{
    /// <summary>
    /// 参数验证过滤器
    /// </summary>
    public class ValidateFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                foreach (var item in context.ModelState.Values)
                {
                    if (item.ValidationState == ModelValidationState.Invalid)
                    {
                        context.Result = JsonResultFactory.Error(item.Errors.FirstOrDefault().ErrorMessage);
                        break;
                    }
                }
            }
        }
    }
}